/**
 * @author  ming
 * @date  2020/6/6 21:31
 * @desc
 */
package controllers

import (
	"github.com/astaxie/beego"
	"strings"
)

type ResultMap struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

type BaseController struct {
	beego.Controller
	Result ResultMap
}

func (c *BaseController) Test() {
	c.SetData("hello bee web")
}

func (c *BaseController) Prepare() {
	method := c.Ctx.Input.Method()
	if strings.ToUpper(method) == "OPTIONS" {
		c.Ctx.Output.SetStatus(204)
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET,POST")
		c.Ctx.Output.Header("Access-Control-Allow-Headers",
			"Origin, No-Cache, X-Requested-With, Cache-Control, Content-Type,Authorization")

		c.ServeJSON(true)
		c.StopRun()
		return
	}
}

func (c *BaseController) Finish() {
	w := c.Ctx.ResponseWriter
	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Max-Age", "600")

	c.Data["json"] = c.Result
	c.ServeJSON()
}

func (c *BaseController) SetData(data interface{}) {
	c.Result.Code = 0
	c.Result.Message = ""
	c.Result.Data = data
}

func (c *BaseController) SetError(code int, message string) {
	c.Result.Code = code
	c.Result.Message = message
	c.Result.Data = nil
}
